/*
 * SpeedoDyno - Speedometer and dynamometer application for Android 
 * Copyright 2013 Guilhem VALENTIN
 * 
 * This file is part of SpeedoDyno
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SpeedoDyno. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gvalentin.speedodyno.data;

import android.location.Location;
import android.util.Log;

/**
 * Calculate speed average
 * @author guilhem
 */
public class CalculatorSpeedAverage implements Calculator<Double> {
	
	private static final String TAG = CalculatorSpeedAverage.class.getSimpleName();
	
	// Minimum speed to consider for average calculation (in m/s) 
	private static final double AVERAGE_MIN_SPEED = 1.0f;
	

	// Data
	private SpeedoDynoData data;
	
	// Total elapsed time (in milliseconds)
	private long totalTime = 0;
	
	// Calculated average
	double speedAvg = 0.0f;

	
	/**
	 * Constructor
	 */
	public CalculatorSpeedAverage(SpeedoDynoData data) {
		this.data = data;
	}
	
	
	/**
	 * Update the current location
	 * @see com.gvalentin.speedodyno.data.Calculator#update(android.location.Location, android.location.Location)
	 */
	@Override
	public void update(Location previous, Location location) {
		if (previous != null && location != null) {
			// Check elapsed time
			long elapsed = location.getTime() - previous.getTime();
			if (elapsed > 0 && elapsed < 10000) {
				double speed = data.getSpeed();
				// Check that power is more than minimum required
				if (speed > AVERAGE_MIN_SPEED) {
					long newTotalTime = totalTime + elapsed;
					
					double newSpeedAvg = speedAvg*totalTime/newTotalTime + speed*elapsed/newTotalTime;
					Log.d(TAG, "update(): speed="+speed+", average="+newSpeedAvg);

					totalTime += elapsed;
					speedAvg = newSpeedAvg;
				}
			}
		}
	}
	
	/**
	 * Get the calculated speed average
	 * @see com.gvalentin.speedodyno.data.Calculator#getData()
	 */
	@Override
	public Double getData() {
		return speedAvg;
	}
}
